import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:rhttp/rhttp.dart';

void main() async {
  await Rhttp.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'HTTP/3 with Flutter and Rust',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: Scaffold(
          appBar: AppBar(
            backgroundColor: Theme.of(context).colorScheme.inversePrimary,
            title: Text('HTTP/3 with Flutter and Rust'),
          ),
          body: HttpTester()),
    );
  }
}

class HttpTester extends StatefulWidget {
  @override
  _HttpTesterState createState() => _HttpTesterState();
}

class _HttpTesterState extends State<HttpTester> {
  String _inputUrl = 'https://cloudflare-quic.com/';
  final TextEditingController _urlController = TextEditingController();
  String _responseHeader = '';
  String _responseBody = '';
  String _summary = '';
  String _deviceDetails = '';

  @override
  void initState() {
    super.initState();
    _urlController.text = _inputUrl;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _getDeviceDetails();
  }

  Future<void> _getDeviceDetails() async {
    String deviceDetails = '';

    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    try {
      if (Theme.of(context).platform == TargetPlatform.android) {
        AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
        deviceDetails = '''
系统名称: Android
设备型号: ${androidInfo.model}
系统版本: ${androidInfo.version.sdkInt}
制造商: ${androidInfo.manufacturer}''';
      } else if (Theme.of(context).platform == TargetPlatform.iOS) {
        IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
        deviceDetails = '''
系统名称: iOS
设备名称: ${iosInfo.name}
系统版本: ${iosInfo.systemVersion}
设备模型: ${iosInfo.model}''';
      } else if (Theme.of(context).platform == TargetPlatform.ohos) {
        OhosDeviceInfo ohosInfo = await deviceInfo.ohosInfo;
        deviceDetails = '''
系统名称: HarmonyOS
设备名称: ${ohosInfo.marketName}
系统版本: ${ohosInfo.osFullName}
设备型号: ${ohosInfo.productModel}''';
      } else {
        deviceDetails = "当前平台不支持";
      }
    } catch (e) {
      deviceDetails = "获取设备信息时出错: $e";
    }

    setState(() {
      _deviceDetails = deviceDetails.trim();
    });
  }

  void _executeRequest() async {
    _inputUrl = _urlController.text;
    if (_inputUrl.isNotEmpty) {
      HttpTextResponse response = await Rhttp.get(_inputUrl,
          settings: const ClientSettings(
            httpVersionPref: HttpVersionPref.http3,
          ));
      setState(() {
        _summary = response.toString();
        _responseBody = response.body;
        _responseHeader = '';
        response.headerMap.forEach((key, value) {
          _responseHeader += '$key: $value\n';
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            width: double.infinity,
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('设备信息:',
                        style: TextStyle(fontWeight: FontWeight.bold)),
                    Text(_deviceDetails),
                  ],
                ),
              ),
            ),
          ),
          Card(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _urlController,
                      decoration: InputDecoration(labelText: '输入URL'),
                    ),
                  ),
                  SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: _executeRequest,
                    child: Text('执行'),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            child: Container(
              width: double.infinity,
              child: Card(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text('Summary:',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                        Text(_summary),
                        SizedBox(height: 20),
                        Text('Headers:',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                        Text(_responseHeader),
                        Text('Body:',
                            style: TextStyle(fontWeight: FontWeight.bold)),
                        Text(_responseBody),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
